# 导包
from sklearn.datasets import make_blobs
import matplotlib.pyplot  as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score,calinski_harabasz_score

# 构建数据
x,y=make_blobs(n_samples=1000,n_features=2,centers=[[-1,-1],[0,0],[1,1],[2,2]],
           cluster_std=[0.4,0.4,0.4,0.2],random_state=22)

# 计算不同K值下的SSE,来获取K值
# sse = []
# for k in range(1,51):
#     km = KMeans(n_clusters=k,max_iter=100,random_state=22)
#     km.fit(x)
#     sse.append(km.inertia_)

# plt.plot(range(1,51),sse)
# plt.grid()
# plt.show()

# 计算SC系数
# sc = []
# for k in range(2,51):
#     km = KMeans(n_clusters=k,max_iter=100,random_state=22)
#     y_pred=km.fit_predict(x)
#     sc_ = silhouette_score(x,y_pred)
#     sc.append(sc_)
#
#
# plt.plot(range(2,51),sc)
# plt.grid()
# plt.show()

ch = []
for k in range(2,51):
    km = KMeans(n_clusters=k,max_iter=100,random_state=22)
    y_pred=km.fit_predict(x)
    ch_ = calinski_harabasz_score(x,y_pred)
    ch.append(ch_)


plt.plot(range(2,51),ch)
plt.grid()
plt.show()